import * as vscode from 'vscode'
import { COMMANDS, CONFIG } from '../constants/commands'
import { RecordListRenderer } from '../ui/recordList'

class RecordViewProvider implements vscode.WebviewViewProvider {
  private _view?: vscode.WebviewView
  private _currentRecords: any[] = []
  private _disposables: vscode.Disposable[] = []
  private renderer: RecordListRenderer

  constructor(private readonly _extensionUri: vscode.Uri, private readonly _context: vscode.ExtensionContext) {
    this.renderer = new RecordListRenderer(_extensionUri)
    this.loadRecords()

    // 监听配置变化
    this._disposables.push(
      vscode.workspace.onDidChangeConfiguration(e => {
        if (e.affectsConfiguration(CONFIG.SHOW_DEBUG_INFO)) {
          console.log('配置变化：showDebugInfo')
          this.refreshWebview()
        }
      })
    )
  }

  // 刷新整个WebView
  private refreshWebview() {
    if (this._view) {
      console.log('刷新WebView视图')
      this._view.webview.html = this.renderer.generateHtml(this._view.webview)
      // 重新发送记录数据
      setTimeout(() => {
        this.updateRecords(this._currentRecords)
      }, 100)
    }
  }

  // 销毁时清理资源
  dispose() {
    this._disposables.forEach(d => d.dispose())
  }

  private loadRecords() {
    const workspaceFolder = vscode.workspace.workspaceFolders?.[0]
    if (!workspaceFolder) {
      this._currentRecords = []
      console.log('没有打开的工作区，记录为空')
      return
    }

    const workspacePath = workspaceFolder.uri.fsPath
    const allRecords = this._context.globalState.get('codememo_workspace_records', {}) as Record<string, any[]>
    this._currentRecords = allRecords[workspacePath] || []
    console.log('loadRecords:', this._currentRecords.length)
  }

  resolveWebviewView(webviewView: vscode.WebviewView, context: vscode.WebviewViewResolveContext, _token: vscode.CancellationToken) {
    this._view = webviewView

    webviewView.webview.options = {
      enableScripts: true,
      localResourceRoots: [this._extensionUri]
    }

    webviewView.onDidChangeVisibility(() => {
      if (webviewView.visible) {
        this.loadRecords()
        setTimeout(() => {
          this.updateRecords(this._currentRecords)
        }, 50)
      }
    })

    webviewView.webview.html = this.renderer.generateHtml(webviewView.webview)

    setTimeout(() => {
      this.loadRecords()
      this.updateRecords(this._currentRecords)
    }, 50)

    // 消息处理
    webviewView.webview.onDidReceiveMessage(async data => {
      await this.handleWebviewMessage(data)
    })
  }

  private async handleWebviewMessage(data: any) {
    switch (data.type) {
      case 'recordClick':
        if (data.recordId) {
          vscode.commands.executeCommand(COMMANDS.RECORD_DETAIL, data.recordId)
        }
        break
      case 'openRecordReference': {
        const record = this._currentRecords.find(r => r.id == data.recordId)
        if (record) {
          vscode.commands.executeCommand(COMMANDS.OPEN_RECORD_REFERENCE, record)
        }
        break
      }
      case 'updateRecordReference':
        if (data.recordId) {
          vscode.commands.executeCommand(COMMANDS.UPDATE_RECORD_REFERENCE, parseInt(data.recordId))
        }
        break
      case 'generateComment':
        if (data.recordId) {
          vscode.commands.executeCommand(COMMANDS.GENERATE_COMMENT, parseInt(data.recordId))
        }
        break
      case 'editRecord':
        const recordToEdit = this._currentRecords.find(r => r.id == data.recordId)
        if (recordToEdit) {
          vscode.commands.executeCommand(COMMANDS.EDIT_RECORD, recordToEdit.id)
        }
        break
      case 'deleteRecord':
        console.log('=== 删除记录开始 ===')
        console.log('recordId:', data.recordId)
        try {
          const result = await vscode.commands.executeCommand(COMMANDS.DELETE_RECORD, parseInt(data.recordId))
          console.log('命令执行结果:', result)
        } catch (error: any) {
          console.error('删除命令执行失败:', error)
          vscode.window.showErrorMessage('删除失败: ' + error.message)
        }
        console.log('=== 删除记录结束 ===')
        break
      case 'filterByTag':
        // 标签筛选功能 - 可以后续扩展
        vscode.window.showInformationMessage(`筛选标签: ${data.tag}`)
        break
    }
  }

  public updateRecords(records: any[]) {
    this._currentRecords = records
    if (this._view && this._view.visible) {
      this._view.webview.postMessage({
        type: 'updateRecords',
        records: records
      })
    }
  }
}

export default RecordViewProvider
